<template>
  <el-dialog :title="title" :visible="dialogVisible" width="50%" @close="close">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="ruleForm.title"></el-input>
      </el-form-item>
      <el-form-item label="文章标题" prop="articleBody">
        <quill-editor v-model="ruleForm.articleBody"></quill-editor>
      </el-form-item>
      <el-form-item label="视频地址">
        <el-input v-model="ruleForm.videoURL"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closedialog">关闭</el-button>
      <el-button type="primary" @click="submitForm(title)">提交</el-button>
    </span>
  </el-dialog>
</template>

<script>
// 引入api
import { update, add } from '@/api/hmmm/articles'
// 导入富文本编辑器
import { quillEditor } from 'vue-quill-editor'
// 导入vue-quill-editor的样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// 局部注册文本编辑器
export default {
  components: {
    quillEditor
  },
  props: {
    title: {
      type: String
    },
    dialogVisible: {
      type: Boolean,
      default: false
    },
    info: {
      type: Object,
      required: false
    }
  },
  data () {
    return {
      ruleForm: {
        title: '',
        articleBody: '',
        videoURL: ''
      },
      rules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        articleBody: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
      }
    }
  },
  // 监听传过来的数据
  watch: {
    info: function (val) {
      console.log(111)
      this.setinfo(val)
    }
  },
  methods: {
    // 对传过来的数据进行表单赋值
    setinfo (info) {
      this.ruleForm = info
    },
    // 重置表单
    resetForm () {
      this.$refs.ruleForm.resetFields()
      this.ruleForm.videoURL = ''
    },
    // 关闭组件
    closedialog () {
      this.$emit('update:dialogVisible', false)
      this.resetForm()
    },
    // 点击取消
    close () {
      this.closedialog()
    },
    // 提交按钮
    submitForm (title) {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (title === '新增文章') {
            const res = await add(this.ruleForm)
            if (res.status !== 200) return this.$message.error('添加失败，请稍后再试！')
            this.$message.success('添加成功!')
          } else {
            const res = await update(this.ruleForm)
            if (res.status !== 200) return this.$message.error('修改失败，请稍后再试！')
            this.$message.success('修改成功!')
          }
          this.close()
          this.$parent.geiinfo()
        } else {
          console.log('请将必填项填写完整')
          return false
        }
      })
    }
  }
}
</script>

<style scoped lang='less'>
::v-deep .quill-editor{
  .ql-editor {
    min-height: 150px ;
  }
}
</style>
